var activityType = 20; //活动类型

var crmCustomerIdOnearry=[]
// 初始化选择商品数据
var selectTable; // table对象
var selectData = []; // 当前页的数据内容
var selectSpuOpen = []; // 目前展开的spu数据
// *****************************************************select 阶段
var joinOtherActivitySkuCodes = []; // 本次已经参加其他活动的skuCode

var selectedSpuCodes = []; // 选中未确认的spu 集合
var selectedSkuCodes = []; // 选中未确认的sku 集合

var setSpuCodes = []; // 已经参加本次活动的spuCode集合
var setSkuCodes = []; // 已经参加本次活动的skuCode集合
var setSkuLists = []; // 已经参加本次活动的sku集合
var setSkuLists_copy = []; // 已经参加本次活动的sku集合,保留上一次设置的数据
var this_activityId = parent.activityId; // 本次活动的id


// *****************************************************set 阶段
var validateForm = $("#form-member").validate({
    rules: {
        "ruleValue-10": "requiredRuleType10",
        "ruleValue-20": "requiredRuleType20",
        "preferentialMost": "requiredPreferentialMost",
        "useCondition-10": "requiredUseCondition10",
        "useCondition-20": "requiredUseCondition10",
        "useCondition-10-1": "requiredUseCondition101",
        "useCondition-20-1": "requiredUseCondition101",
        "useCondition-10-2": "requiredUseCondition101",
        "useCondition-20-2": "requiredUseCondition101",
        "useCondition-10-3": "requiredUseCondition101",
        "useCondition-20-3": "requiredUseCondition101",
        "useCondition-10-4": "requiredUseCondition101",
        "useCondition-20-4": "requiredUseCondition101",
        "useCondition-10-5": "requiredUseCondition101",
        "useCondition-20-5": "requiredUseCondition101",
        "useCondition-10-6": "requiredUseCondition101",
        "useCondition-20-6": "requiredUseCondition101",
        "useCondition-10-7": "requiredUseCondition101",
        "useCondition-20-7": "requiredUseCondition101",
        "useCondition-10-8": "requiredUseCondition101",
        "useCondition-20-8": "requiredUseCondition101",
        "useCondition-10-9": "requiredUseCondition101",
        "useCondition-20-9": "requiredUseCondition101",
        "useCondition-10-10": "requiredUseCondition101",
        "useCondition-20-10": "requiredUseCondition101",

        "roleValue-count-1": "requiredRoleValueCount1",
        "roleValue-count-2": "requiredRoleValueCount1",
        "roleValue-count-3": "requiredRoleValueCount1",
        "roleValue-count-4": "requiredRoleValueCount1",
        "roleValue-count-5": "requiredRoleValueCount1",
        "roleValue-count-6": "requiredRoleValueCount1",
        "roleValue-count-7": "requiredRoleValueCount1",
        "roleValue-count-8": "requiredRoleValueCount1",
        "roleValue-count-9": "requiredRoleValueCount1",
        "roleValue-count-10": "requiredRoleValueCount1",

        "roleValue-reduce-1": "requiredRoleValueReduce1",
        "roleValue-reduce-2": "requiredRoleValueReduce1",
        "roleValue-reduce-3": "requiredRoleValueReduce1",
        "roleValue-reduce-4": "requiredRoleValueReduce1",
        "roleValue-reduce-5": "requiredRoleValueReduce1",
        "roleValue-reduce-6": "requiredRoleValueReduce1",
        "roleValue-reduce-7": "requiredRoleValueReduce1",
        "roleValue-reduce-8": "requiredRoleValueReduce1",
        "roleValue-reduce-9": "requiredRoleValueReduce1",
        "roleValue-reduce-10": "requiredRoleValueReduce1",

    },
    submitHandler: function (from) {

        addReduceActivity();
    }
});


/**********************************************************表单区域*****************************************************************************************/
// 当活动商品中存在已选值，在切换活动对象时，弹层提示：“切换活动对象，将清空已选活动商品”，点击确定，执行；点击取消，不执行
changeActivityPerson();
//$('#enableCategoryDiscount').attr("disabled", true);
var activityPerson_before = $("#activityPerson").val();
$("#activityPerson").change(function () {
    // 只有当选择了签约客户（分销或非分销），可以设置品类折扣率的商品参与还是不参与
    var activityPerson = $("#activityPerson").val();
    if (selectData.length > 0 || setSkuLists.length > 0) {
        // 1 清空商品列表
        layer.confirm('切换活动对象，将清空已选活动商品', function (index) {
            activityPerson_before = activityPerson;
            resetTable();
            changeActivityPerson();
            payWayChange($("#payWay-9999"));
            layer.close(index);
        }, function () {
            $("#activityPerson").val(activityPerson_before);
        });
    } else {
        changeActivityPerson();
        payWayChange($("#payWay-9999"));
        activityPerson_before = activityPerson;
    }
});

function resetTable() {
    resetSelectTable();
    resetSetTable();
}

function resetSelectTable() {
    // 1 清除商品数据
    selectData = []; // 当前页的数据内容
    selectSpuOpen = []; // 目前展开的spu数据
    joinOtherActivitySkuCodes = []; // 本次已经参加其他活动的skuCode
    selectedSpuCodes = []; // 选中未确认的spu 集合
    selectedSkuCodes = []; // 选中未确认的sku 集合
    setSpuCodes = []; // 已经参加本次活动的spuCode集合
    setSkuCodes = []; // 已经参加本次活动的skuCode集合
    setSkuLists = []; // 已经参加本次活动的sku集合
    setSkuLists_copy = []; // 已经参加本次活动的sku集合,保留上一次设置的数据
    initSelectDataTable(selectData);
    initPage(0);
}

function resetSetTable() {
    lessCost = []; // 小于成本价的商品
    overNum = []; // 存在超卖
    setTablsDatas;
    setChecked = []; // 选中的数据
    initSetDataTable();
}

function changeActivityPerson() {
    var activityPerson = $("#activityPerson").val();
    if (activityPerson == 20 || activityPerson == 30) {
        $('#discount').show();
        //$('#enableCategoryDiscount').attr("disabled", false);
        $("#payWay-1101").prop("checked", false);
        $("#payWay-1201").prop("checked", false);
        $("#payWay-1701").prop("checked", false);
        $("#payWay-1101-show").show();
        $("#payWay-1201-show").show();
        $("#payWay-1701-show").hide();
    } else {
        $("#payWay-1101").prop("checked", false);
        $("#payWay-1201").prop("checked", false);
        $("#payWay-1701").prop("checked", false);
        $("#payWay-1101-show").hide();
        $("#payWay-1201-show").hide();
        $('#discount').hide();
        $("#payWay-1701-show").show();
        //$('#enableCategoryDiscount').attr("disabled", true);
    }
}

// 支付方式checkbox变化事件
function payWayChange(obj) {
    console.log($(obj).val());
    if ($(obj).val() == 9999) {
        $("#payWay-1001").prop("checked", $(obj).is(':checked'));
        $("#payWay-1301").prop("checked", $(obj).is(':checked'));
        $("#payWay-1401").prop("checked", $(obj).is(':checked'));
        $("#payWay-1701").prop("checked", $(obj).is(':checked'));

        if (!$("#payWay-1101").is(":hidden")) {
            $("#payWay-1101").prop("checked", $(obj).is(':checked'));
        }
        if (!$("#payWay-1201").is(":hidden")) {
            $("#payWay-1201").prop("checked", $(obj).is(':checked'));
        }
    } else {
        if ($("#payWay-1001").is(":checked") &&
            $("#payWay-1301").is(":checked") &&
            $("#payWay-1401").is(":checked") &&
            $("#payWay-1101").is(":checked") &&
            $("#payWay-1201").is(":checked") &&
            !$("#payWay-1101").is(":hidden") &&
            !$("#payWay-1201").is(":hidden")
        ) {
            $("#payWay-9999").prop("checked", true);
        } else if (
            $("#payWay-1001").is(":checked") &&
            $("#payWay-1301").is(":checked") &&
            $("#payWay-1401").is(":checked") &&
            $("#payWay-1101").is(":hidden") &&
            $("#payWay-1701").is(":checked") &&
            $("#payWay-1201").is(":hidden")
        ) {
            $("#payWay-9999").prop("checked", true);
        } else {
            $("#payWay-9999").prop("checked", false);
        }
    }
}

// 当活动商品中存在已选值，在切换活动区域时，弹层提示：“切换活动区域，将清空已选活动商品”，点击确定，执行；点击取消，不执行
var activityLocation_before = $("#activityLocation").val();
$("#activityLocation").change(function () {
    if (selectData.length > 0 || setSkuLists.length > 0) {
        // 1 清空商品数据
        layer.confirm('切换活动区域，将清空已选活动商品', function (index) {
            //  清除商品数据
            resetTable();
            activityLocation_before = $("#activityLocation").val();
            layer.close(index);
        }, function () {
            $("#activityLocation").val(activityLocation_before);
        });
    } else {
        activityLocation_before = $("#activityLocation").val();
    }
});

// 平台chenkbox选择时动态控制url两个input框

$("#platform-10").change(function () {
    if ($('#platform-10').is(':checked')) {
        $('#adPcUrl').attr("disabled", false);
        $('#adAppUrl').attr("disabled", false);
        // 全选
        $('#platform-20').prop("checked", true);
        $('#platform-30').prop("checked", true);
        return;
    } else {
        $('#platform-20').prop("checked", false);
        $('#platform-30').prop("checked", false);
        $('#adPcUrl').attr("disabled", true);
        $('#adAppUrl').attr("disabled", true);
    }
});
$("#platform-20").change(function () {
    if ($('#platform-20').is(':checked')) {
        if ($('#platform-30').is(':checked')) {
            $('#platform-10').prop("checked", true);
        } else {
            $('#platform-10').prop("checked", false);
        }
        $('#adPcUrl').attr("disabled", false);
    } else {
        $('#platform-10').prop("checked", false);
        $('#adPcUrl').val("");
        $('#adPcUrl').attr("disabled", true);
    }
});
$("#platform-30").change(function () {
    if ($('#platform-30').is(':checked')) {
        if ($('#platform-20').is(':checked')) {
            $('#platform-10').prop("checked", true);
        } else {
            $('#platform-10').prop("checked", false);
        }
        $('#adAppUrl').attr("disabled", false);
    } else {
        $('#platform-10').prop("checked", false);
        /*if (this_activityId <= 0) {
            $('#adAppUrl').val("");
        }*/
        $('#adAppUrl').val("");
        $('#adAppUrl').attr("disabled", true);
    }
});

function platformChange() {
    if ($('#platform-10').is(':checked')) {
        $('#adPcUrl').attr("disabled", false);
        $('#adAppUrl').attr("disabled", false);
        return;
    } else {
        $('#adPcUrl').attr("disabled", true);
        $('#adAppUrl').attr("disabled", true);
    }
    if ($('#platform-20').is(':checked')) {
        $('#adPcUrl').attr("disabled", false);
    } else {
        /*if (this_activityId <= 0) {
            $('#adPcUrl').val("");
        }*/
        $('#adPcUrl').val("");
        $('#adPcUrl').attr("disabled", true);
    }
    if ($('#platform-30').is(':checked')) {
        $('#adAppUrl').attr("disabled", false);
    } else {
        /* if (this_activityId <= 0) {
             $('#adAppUrl').val("");
         }*/
        $('#adAppUrl').val("");
        $('#adAppUrl').attr("disabled", true);
    }
}

initAcvicityLoation();

// 初始化活动区域
function initAcvicityLoation() {
    $.ajax({
        url: root.promotion.search_activity_location,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: {},
        async: false,
        success: function (data) {
            if (data != null && data.errorCode == 0) {
                for (let i = 0; i < data.data.length; i++) {
                    const obj = data.data[i];
                    if(obj.warehouse_data_type !=2){
                    $("#activityLocation").append("<option value=" + obj.id + ">" + obj.warehouse_name + "</option>");
                }
            }
            } else {
                layer.msg('活动区域初始化失败', {
                    icon: 2,
                    time: 3000
                });
            }
        },
        error: function () {
            console.log("!!!!活动区域初始化失败!!!!");
            layer.msg('活动区域初始化失败', {
                icon: 2,
                time: 3000
            });
        }
    });
}


// 当选择了参与，默认为全部，后面的输入框隐藏，当选择其他选项时，需要输入，默认100%，正数，可保留小数点后两位，为必填项
changeEnableCategoryDiscount();
$("#categoryDiscountRule_show").hide();
$("#categoryDiscount_show").hide();
$("#enableCategoryDiscount").change(function () {
    changeEnableCategoryDiscount();
});

function changeEnableCategoryDiscount() {
    var enableCategoryDiscount = $("#enableCategoryDiscount").val();
    if (enableCategoryDiscount == 10) { // 当选择参与,默认品类折扣率无限制,输入框隐藏
        $("#categoryDiscountRule_show").show();
        $("#categoryDiscount_show").hide();
    } else {
        $("#categoryDiscountRule").val("10")
        $("#categoryDiscountRule_show").hide();
        $("#categoryDiscount_show").hide();
    }
}

changeCategoryDiscountRule();
$("#categoryDiscountRule").change(function () {
    changeCategoryDiscountRule();
});

function changeCategoryDiscountRule() {
    var categoryDiscountRule = $("#categoryDiscountRule").val();
    if (categoryDiscountRule == 20 || categoryDiscountRule == 30) {
        $("#categoryDiscount").val(100.00);
        $("#categoryDiscount_show").show();
    } else {
        $("#categoryDiscount_show").hide();
    }
}

/**********************************************************表格 select 区域*****************************************************************************************/
// 动态控制模板和文件上传
//下载模板
$('#dowmloadTemplate').attr('href', root.promotion.download_single_product_template + '?type=20');
selectP();

// 选择商品tab点击事件
function selectP() {
    $("#template").hide();
    renderStyle();
}

// 设置商品点击事件
function setP() {
    $("#template").show();
    initSetDataTable();
    console.log(setSkuLists);
}

var activityPerson_before = $("#activityPerson").val();
$("#class1").change(function () {
    changeClass(1);
});
$("#class2").change(function () {
    changeClass(2);
});
$("#class3").change(function () {
    changeClass(3);
});

// 类目选择变动函数
function changeClass(level) {
    // 一级类目点击事件,重新加载二级类目,清空三级类目内容
    if (level == 1) {
        $("#class2").empty();
        $("#class2").append("<option value=''>请选择二级品类名称</option>");
        $("#class3").empty();
        $("#class3").append("<option value=''>请选择三级品类名称</option>");
    }
    // 二级类目点击事件,重新加载三级类目
    if (level == 2) {
        $("#class3").empty();
        $("#class3").append("<option value=''>请选择三级品类名称</option>");
    }
    if ($("#class" + level).val() != "") {
        initClass(level, {
            "parentCateId": $("#class" + level + "").val()
        })
    }

}

// 结束时间选择事件
function endTimeChange() {
    if ($("#startTime").val().trim() == "") {
        layer.msg('请先选择开始时间', {
            icon: 2,
            time: 3000
        });
        $("#endTime").val("");
    }
}

/*// 初始化一级类目
initClass(0, {
    "categoryLevel": 1
});

function initClass(level, data) {
    $.ajax({
        url: root.goodsInter.categoryByParam,
        cache: false, //禁用缓存
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        type: "POST",
        data: data,
        success: function (data) {
            if (data != null && data.data.length > 0) {
                // 初始化一级类目
                if (level == 0) {
                    for (var i = 0; i < data.data.length; i++) {
                        $("#class1").append("<option value='" + data.data[i].category_id + "'>" + data.data[i].category_name + "</option>");
                    }
                } else {
                    level = level + 1;
                    /!* $("#class" + level + "").empty();*!/
                    for (var i = 0; i < data.data.length; i++) {
                        $("#class" + level).append("<option value='" + data.data[i].category_id + "'>" + data.data[i].category_name + "</option>");
                    }
                }
            }
        },
        error: function () {
            console.log("!!!!获取商品类目异常-商品后台!!!!");
            layer.msg('获取商品类目异常-商品后台', {
                icon: 2,
                time: 3000
            });
        }
    });
}*/


// 获取搜索条件
function getSearchCondition() {
    let _categoryLevel = null;
    let _categoryId = null;
    if(JSON.stringify(_categoryData) != "{}" && _categoryData.categoryId4){
        _categoryLevel = 4;
        _categoryId = _categoryData.categoryId4;
    }
    if(JSON.stringify(_categoryData) != "{}" && !_categoryData.categoryId4){
        _categoryLevel = 3;
        _categoryId = _categoryData.categoryId3;
    }
    if(JSON.stringify(_categoryData) != "{}" && !_categoryData.categoryId3){
        _categoryLevel = 2;
        _categoryId = _categoryData.categoryId2;
    }
    if(JSON.stringify(_categoryData) != "{}" && !_categoryData.categoryId2){
        _categoryLevel = 1;
        _categoryId = _categoryData.categoryId1;
    }
    var json = {
        "categoryId": _categoryId,
        "categoryLevel": _categoryLevel,
        "spuCode": $("#spuCode").val() == "" ? null : $("#spuCode").val(),
        "skuCode": $("#skuCode").val() == "" ? null : $("#skuCode").val(),
        "productCode": $("#productCode").val() == "" ? null : $("#productCode").val(),
        "helpCode": $("#helpCode").val() == "" ? null : $("#helpCode").val(),
        "spuName": $("#spuName").val() == "" ? null : $("#spuName").val(),
        "saleStatus": $("#state").val() == "" ? null : $("#state").val(),
        "warehouseId": $("#activityLocation").val() == "" ? null : $("#activityLocation").val(),
        "brandId": $("#brand").val() == "" ? null : $("#brand").val(),
        "customerType": $("#activityPerson").val() == "" ? null : $("#activityPerson").val(),
        "beginTime": $("#startTime").val(),
        "endTime": $("#endTime").val()
    };
    return json
}

// 查询按钮
function searchProduct() {
    if ($("#activityPerson").val().trim() == "" || $("#activityLocation").val().trim() == "" || $("#startTime").val().trim() == "") {
        var msg = "请先选择";
        msg += $("#activityPerson").val().trim() == "" ? "[活动对象] " : "";
        msg += $("#activityLocation").val().trim() == "" ? "  [活动区域]" : "";
        msg += $("#startTime").val().trim() == "" ? "  [开始时间]" : "";
        layer.msg(msg, {
            icon: 5,
            time: 3000
        });
        return;
    }
    $.ajax({
        url: root.promotion.goods_find_activity_products,
        cache: false, //禁用缓存
        type: "POST",
        dataType: "json",
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify({
            "model": getSearchCondition(),
            "pageSize": 50,
            "nowPage": 1
        }),
        success: function (data) {
            console.log(data);
            initSelect(gettconverToProductBean(data));
            renderStyle();
            initPage(data.data.totalPage)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest, textStatus, errorThrown);
            console.log("!!!!获取商品数据异常-商品后台!!!!")
        }
    });
}

function initPage(total) {
    $('.M-box3').pagination({
        pageCount: total,
        jump: true,
        coping: true,
        prevContent: '上页',
        nextContent: '下页',
        callback: function (api) {
            $.ajax({
                url: root.promotion.goods_find_activity_products,
                cache: false, //禁用缓存
                type: "POST",
                dataType: 'json',
                contentType: 'application/json; charset=UTF-8',
                async: false,
                data: JSON.stringify({
                    "model": getSearchCondition(),
                    "pageSize": 50,
                    "nowPage": api.getCurrent()
                }),
                success: function (result) {
                    initSelect(gettconverToProductBean(result));
                    renderStyle();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log("!!!!获取商品数据异常-商品后台!!!!")
                }
            })
            ;
        }
    });
}

function initSelect(data) {
    console.log(data);
    selectData = data;
    // 初始化表格
    initSelectDataTable(data);
    // 清空数据
    selectSpuOpen = []; // 目前展开的spu数据
    // 初始化参加其他活动的商品数据
    initOtherActivitieSkuCode(data);
    // 初始化参加本次商品的数据
    initsetSkuCodes(data)
    // 初始化全选按钮
    $("#example-select-all").prop("checked", false);
}

//*********************************************************初始化参加其他活动的数组,和选择商品table
//初始化已经参加其他活动的数据
function initOtherActivitieSkuCode(result) {
    /* joinOtherActivitySkuCodes = [];*/
    for (let i = 0; i < result.length; i++) {
        var skus = result[i]._skus;
        for (let j = 0; j < skus.length; j++) {
            // 活动id不为空,且不等于本次活动id
            if (skus[j]._activityId != null && skus[j]._activityId != this_activityId) {
                if (joinOtherActivitySkuCodes.indexOf(skus[j]._skuCode) <= -1) {
                    joinOtherActivitySkuCodes.push(skus[j]._skuCode);
                }
            }
        }
    }
}

// 初始化本页已经参加活动的数据
function initsetSkuCodes(data) {
    for (let i = 0; i < data.length; i++) {
        var skus = data[i]._skus;
        var spuCode = data[i]._spuCode;
        // 处理已经参加其他活动的spucode
        if (data[i]._activityId != null && data[i]._activityId != 0) {
            insertToSetSpu(spuCode);
        }
        for (let j = 0; j < skus.length; j++) {
            // 活动id不为空,且不等于本次活动id
            if (skus[j]._activityId != null && skus[j]._activityId == this_activityId) {
                if (setSkuCodes.indexOf(skus[j]._skuCode) <= -1) {
                    setSkuCodes.push(skus[j]._skuCode);
                }
                insertToSetSkuLists(skus[j]);

            }
        }
    }
}

// 清空table
function clearTable() {
    var dttable = $('#selectProduct').dataTable(); // 初始化dataTable，清空上一个值
    if (dttable) {
        dttable.fnDestroy(); //还原初始化了的datatable
        dttable.fnClearTable(); //清空一下table
        selectTable = '';
    }
}

// 初始化 选择商品table
function initSelectDataTable(data) {
    clearTable();
    selectTable = $("#selectProduct").DataTable({
        "autoWidth": false, // 自动宽度
        "ordering": false, // 开启排序
        "searching": false, //
        "paging": false,
        "serverSide": false, //启用服务器端分页
        "pagingType": "simple_numbers",
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": false,
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='../../static/h-ui.admin/images/loading.gif' />",
        },
        "data": data,
        "columns": [{
            "data": "_spuCode",
            "orderable": false,
            "className": "dt-body-center",
            "render": function (data, type, row) {
                return '<input id="spu-' + data + '" name="oneCheckbox"  onclick="oneSpuCheckboxClick(\'' + data + '\')" type="checkbox" class="checkbox mr-5">'
            }
        },
            {
                "data": "_spuCode",
                "type": "string"
            },
            {
                "data": "_spuName",
                "type": "string"
            },
            {
                "data": "_brand",
                "type": "string"
            },
           /* {
                "data": "_area",
                "type": "string"
            },*/
            {
                "data": "_shelveNum",
                "type": "string"
            },
            {
                "data": "_costPrice"
            },
            {
                "data": "_tradePrice"
            },
            {
                "data": "_Prices"
            },
            {
                "data": null,
                "defaultContent": ""
            },
            {
                "data": "_state",
                "type": "string"
            },
            {
                "data": "_spuCode",
                "type": "string",
                "render": function (data, type, row) {
                    return '<input type="button" id="button-' + data + '" onclick="joinActiviyBySPU(\'' + data + '\')" class="btn btn-secondary size-S radius mr-10" value="参加活动">';
                }
            },
            {
                "data": null,
                "defaultContent": '<a href="javascript:void(0)"  onclick="showOrhide(this)" class="ml-10">展开</a>'
            }
        ]
    });
}

// 展开收起*********************
function showOrhide(ev) {
    var tr = $(ev).closest('tr');
    var row = selectTable.row(tr);
    var rdata = selectTable.row(tr).data();
    if (row.child.isShown()) {
        $(ev).html("展开");
        row.child.hide();
        //  收起事件,从展开队列移除
        deleteFromSelectSpuOpen(rdata._spuCode);
    } else {
        // 收起事件,添加到展开队列
        insertToSelectSpuOpen(rdata._spuCode);
        $(ev).html("收起");
        // 填充内容
        row.child(showHide(row.data())).show();
        // 选中所有子节点的checkbox
        selectChildCheckbox(rdata._spuCode);
        // 改变所有子节点的按钮样式
        changeChildButton(rdata._spuCode);
    }
}


// 拼接sku html
function getChildHtml(spuCode) {
    var skus = selectSkusBySpu(spuCode);
    var html = "";
    if (skus && skus.length > 0) {
        for (let i = 0; i < skus.length; i++) {
            var checkboxEnable = ''; // checkbox是否可选
            var joinHtml = ''; //参加活动的按钮
            if (joinOtherActivitySkuCodes.indexOf(skus[i]._skuCode) > -1) { // 参加了其他活动
                checkboxEnable = 'disabled'
                joinHtml = '<a href="javascript:void(0)" class="c-999" style="margin-left:0px">已参加其他活动</a>'
            } else if (setSkuCodes.indexOf(skus[i]._skuCode) > -1) { // 已参加本次活动
                checkboxEnable = 'disabled';
                if (skus[i]._activityId > 0) {
                    joinHtml = ' <a href="javascript:void(0)" id="button-' + skus[i]._skuCode + '" class="already_attend" style="margin-left:0px" >已参加其他活动</a>\n'
                } else {
                    joinHtml = ' <a href="javascript:void(0)" id="button-' + skus[i]._skuCode + '" class="already_attend" style="margin-left:0px" onmouseenter="onSkuJoinShow(this)">已参加</a>\n' +
                        '             <input id="button-' + skus[i]._skuCode + '" type="button"  onclick="cancelActiviyBySKU(\'' + skus[i]._activityId + '\',\'' + spuCode + '\',\'' + skus[i]._skuCode + '\')" class="btn btn-warning size-S radius" value="取消参加" style="display: none;margin-left:0px" onmouseleave="onSkucancelShow(this)">';
                }
            } else {
                //  参加活动点击事件
                joinHtml = '<a href="javascript:void(0)" class="styleRight" id="button-' + skus[i]._skuCode + '" style="margin-left:0px" onclick="joinActiviyBySKU(\'' + skus[i]._activityId + '\',\'' + spuCode + '\',\'' + skus[i]._skuCode + '\')">参加活动</a>';
            }
            html += '<ul class="clearfix" style="width: 100%">\n' +
                '\t\t<li class="f-l text-l" style="width:1.5%;height:30px;text-align: center;"></li>\n' +
                '\t\t<li class="f-l text-l" style="width:10%;height:30px;text-align: center;"></li>\n' +
                '\t\t<li class="f-l text-l" style="width:10%;height:30px;text-align: center;"></li>\n' +
                '\t\t<li class="f-l text-l" style="width:8%;height:30px;text-align: center;"></li>\n' +
                '\t\t<li class="f-l text-l" style="width:10%;text-align: center;"><input id="sku-' + skus[i]._skuCode + '" onclick="oneSkuCheckboxClick(\'' + spuCode + '\',\'' + skus[i]._skuCode + '\')" type="checkbox" class="checkbox mr-5" ' + checkboxEnable + '>' + skus[i]._standard + '</li>\n' +
                '\t\t<li class="f-l text-l" style="width:10%;text-align: center;">' + skus[i]._costPrice + '</li>\n' +
                '\t\t<li class="f-l text-l" style="width:10%;text-align: center;">' + skus[i]._tradePrice + '</li>\n' +
                '\t\t<li class="f-l text-l" style="width:10%;text-align: center;">' + skus[i]._Prices + '</li>\n' +
                '\t\t<li class="f-l text-l" style="width:10.5%;text-align: center;">' + skus[i]._unit + '</li>\n' +
                '\t\t<li class="f-l text-l" style="width:7%;text-align: center;">' + skus[i]._salesStatus + '</li>\n' +
                '\t\t<li class="f-l text-l" style="width:7.5%;text-align: center;">\n' +
                joinHtml +
                '\t\t</li>\n' +
                '\t\t<li class="f-l text-l" style="width:4.5%;"></li>\n' +
                '\t</ul>'
        }
    }
    return html;
}

// 翻页重新渲染checkbox和button样式
function renderStyle() {
    // 本页的全部spu
    if (selectData.length > 0) {
        for (let i = 0; i < selectData.length; i++) {
            const SPU = selectData[i];
            if (setSpuCodes.indexOf(SPU._spuCode) > -1) {
                jionSpuButton(SPU._spuCode, SPU._activityId > 0 ? false : true);
            } else {
                cancelSpuButton(SPU._spuCode);
            }
        }
    }
}

//******************************************************************************************checkbox 事件************
// 全选checkbox点击事件
function selectAll(ev) {
    var rows = selectTable.rows({
        'search': 'applied'
    }).nodes();
    /* $(rows).toggleClass('selected');*/
    for (let i = 0; i < rows.data().length; i++) {
        // 加入设置暂存队列
        var skus = selectSkusBySpu(rows.data()[i]._spuCode);
        // 选中所有父节点
        if (!($("#spu-" + rows.data()[i]._spuCode + "").prop('disabled') == true)) {
            if (ev.checked) {
                insertToToBeConfirmSpu(rows.data()[i]._spuCode);
                for (let j = 0; j < skus.length; j++) {
                    insertToToBeConfirmSku(skus[j]._skuCode);
                }
            } else {
                deleteFromToBeConfirmSpu(rows.data()[i]._spuCode);
                for (let j = 0; j < skus.length; j++) {
                    deleteFromToBeConfirmSku(skus[j]._skuCode);
                }
            }
            $("#spu-" + rows.data()[i]._spuCode + "").prop("checked", ev.checked);
            // 子节点选中事件
            selectChildCheckbox(rows.data()[i]._spuCode);
        }
    }
}

// 单个spucheckbox点击事件
function oneSpuCheckboxClick(spuCode) {
    // 将所有的skuCode添加加入待确认队列
    insetOrDeleteToBeConfirm(spuCode);
    selectChildCheckbox(spuCode);
}

// 单个skucheckbox点击事件
function oneSkuCheckboxClick(spuCode, skuCode) {
    if ($("#sku-" + skuCode + "").is(':checked')) {
        insertToToBeConfirmSku(skuCode);
    } else {
        deleteFromToBeConfirmSku(skuCode);
    }
    changParentCheckbox(spuCode, skuCode);
}

// 判断是否需要选中父节点
function changParentCheckbox(spuCode, skuCode) {
    // 判断所有可用的子节点的checked状态
    var skus = selectSkusBySpu(spuCode);
    var checked = true;
    for (let i = 0; i < skus.length; i++) {
        // 如果不可选
        if (!($("#sku-" + skus[i]._skuCode + "").prop('disabled') == true) && $("#sku-" + skus[i]._skuCode + "").is(':checked')) {
            checked = true;
        } else {
            checked = false;
            break;
        }
    }
    if (checked) {
        insertToToBeConfirmSpu(spuCode);
    } else {
        deleteFromToBeConfirmSpu(spuCode);
    }
    $("#spu-" + spuCode + "").prop("checked", checked);
}

// 选中所有子节点的checkbox,只改变样式
function selectChildCheckbox(spuCode) {
    if (selectSpuOpen.indexOf(spuCode) > -1) {
        for (let i = 0; i < selectData.length; i++) {
            if (selectData[i]._spuCode == spuCode) {
                var skus = selectData[i]._skus;
                for (let j = 0; j < skus.length; j++) {
                    if ($("#spu-" + spuCode + "").is(':checked')) {
                        selectedSkuCheckBox(skus[j]._skuCode);
                    } else {
                        cancelSelectedSkuCheckBox(skus[j]._skuCode);
                    }
                }
            }
        }
    }
}

// 根据spucodu 选中所有的sku,或移除所有sku
function insetOrDeleteToBeConfirm(spuCode) {
    for (let i = 0; i < selectData.length; i++) {
        if (selectData[i]._spuCode == spuCode) {
            var skus = selectData[i]._skus;
            if ($("#spu-" + spuCode + "").is(':checked')) {
                insertToToBeConfirmSpu(spuCode);
                for (let j = 0; j < skus.length; j++) {
                    insertToToBeConfirmSku(skus[j]._skuCode);
                }
            } else {
                deleteFromToBeConfirmSpu(spuCode);
                for (let j = 0; j < skus.length; j++) {
                    deleteFromToBeConfirmSku(skus[j]._skuCode);
                }
            }
        }
    }
}

//*****************************************************button 事件****************************************************************
// spu button 加入
function joinActiviyBySPU(spuCode) {
    // 将节点点加入活动队列
    insertToSetSpu(spuCode);
    // spu级别的button文本
    jionSpuButton(spuCode, true);
    // 此代码为下一个函数的前置
    var skus = selectSkusBySpu(spuCode);
    for (let i = 0; i < skus.length; i++) {
        insertToSetSku(spuCode, skus[i]._skuCode);
    }
    // 设置所有子节点为参加状态
    changeChildButton(spuCode);
}

//spu级别的button文本,只改变样式
function jionSpuButton(spuCode, showCancel) {

    var spuActivityId = getActivityBySpuCode(spuCode);
    if (spuActivityId == -1 || (spuActivityId > 0 && spuActivityId == this_activityId)) {
        // 变化文本
        $("#button-" + spuCode + "").parent().html(' <a href="javascript:void(0)" class="already_attend" style="margin-left:0px">已参加其他活动</a>');
    } else if (spuActivityId > 0 && spuActivityId != this_activityId) {
        $("#button-" + spuCode + "").parent().html(' <a href="javascript:void(0)" class="already_attend" style="margin-left:0px">已参加其他活动</a>');
    } else if (spuActivityId == 0) {
        $("#button-" + spuCode + "").parent().html(' <a href="javascript:void(0)" class="already_attend" onmouseenter="onSkuJoinShow(this)" style="margin-left:0px">已参加</a>\n' + ' <input id="button-' + spuCode + '"  onclick="cancelActiviyBySPU(\'' + spuCode + '\')" type="button" class="btn btn-warning size-S radius" onmouseleave="onSkucancelShow(this)" value="取消参加" style="display:none;">');
    }
    /*    if (showCancel) {
            // 变化文本
            $("#button-" + spuCode + "").parent().html(' <a href="javascript:void(0)" class="already_attend" onmouseenter="onSkuJoinShow(this)" style="margin-left:0px">已参加</a>\n' + ' <input id="button-' + spuCode + '"  onclick="cancelActiviyBySPU(\'' + spuCode + '\')" type="button" class="btn btn-warning size-S radius" onmouseleave="onSkucancelShow(this)" value="取消参加" style="display:none;">');
        } else {
            // 变化文本
            $("#button-" + spuCode + "").parent().html(' <a href="javascript:void(0)" class="already_attend" style="margin-left:0px">已参加其他活动</a>');
        }*/
    // 设置checbox 不可用
    $("#spu-" + spuCode + "").prop("checked", false);
    $("#spu-" + spuCode + "").prop("disabled", true);
}

// sku button 取消
function cancelActiviyBySPU(spuCode) {
    // 移除spu级别活动队列
    deleteFromSetSpu(spuCode);
    // 改变本节点的样式
    cancelSpuButton(spuCode);
    // 此代码为下一个函数的前置
    var skus = selectSkusBySpu(spuCode);
    for (let i = 0; i < skus.length; i++) {
        deleteFromSetSku(spuCode, skus[i]._skuCode);
    }
    // 改变子节点的样式和队列
    changeChildButton(spuCode);
}

// spu级别的button文本
function cancelSpuButton(spuCode) {
    // 变化文本
    $("#button-" + spuCode + "").parent().html('<input type="button" id="button-' + spuCode + '" onclick="joinActiviyBySPU(\'' + spuCode + '\')" class="btn btn-secondary size-S radius mr-10" value="参加活动">');
    $("#spu-" + spuCode + "").prop("disabled", false);
}

// 根据skucode参加活动,sku 参加活动点击事件
function joinActiviyBySKU(activityId, spuCode, skucode) {
    // 加入本次活动队列
    insertToSetSku(spuCode, skucode);
    cancelSelectedSkuCheckBox(skucode);
    if (activityId > 0) {
        $("#button-" + skucode + "").parent().html('<a href="javascript:void(0)" class="already_attend" style="margin-left:0px" >已参加其他活动</a>');
    } else {
        $("#button-" + skucode + "").parent().html('<a href="javascript:void(0)" class="already_attend" style="margin-left:0px" onmouseenter="onSkuJoinShow(this)">已参加</a>\n' +
            '             <input type="button" id="button-' + skucode + '" onclick="cancelActiviyBySKU(\'' + activityId + '\',\'' + spuCode + '\',\'' + skucode + '\')" class="btn btn-warning size-S radius" value="取消参加" style="display: none;margin-left:0px" onmouseleave="onSkucancelShow(this)">');
    }
    // checkbox 置灰
    $("#sku-" + skucode + "").prop("disabled", true);
    // 改变父节点的状态
    changParentButton(spuCode);
}

// 根据skucode取消参加活动 取消活动点击事件
function cancelActiviyBySKU(activityId, spuCode, skucode) {
    // 从本次活动队列移除
    deleteFromSetSku(spuCode, skucode);
    // 改变样式,checkbox 可选
    $("#button-" + skucode + "").parent().html('<a href="javascript:void(0)" id="button-' + skucode + '" style="margin-left:0px" onclick="joinActiviyBySKU(\'' + activityId + '\',\'' + spuCode + '\',\'' + skucode + '\')">参加活动</a>');
    $("#sku-" + skucode + "").prop("disabled", false);
    // 改变父节点的状态
    changParentButton(spuCode);
}

// 子节点变化时,改变父节点的状态
function changParentButton(spuCode) {
    // 如果子节点全部为参加活动,该变父节点为参加活动
    var join = false;
    var skus = selectSkusBySpu(spuCode);
    for (let i = 0; i < skus.length; i++) {
        if (joinOtherActivitySkuCodes.indexOf(skus[i]._skuCode) > -1 || setSkuCodes.indexOf(skus[i]._skuCode) > -1) {
            join = true;
        } else {
            join = false;
            break;
        }
    }
    if (join) {
        insertToSetSpu(spuCode);
        jionSpuButton(spuCode, true);
    } else {
        deleteFromSetSpu(spuCode);
        cancelSpuButton(spuCode);
    }
}

// 改变所有子节点的样式
function changeChildButton(spuCode) {
    // 如果spu下面有参加活动的skucode
    var skus = selectSkusBySpu(spuCode);
    for (let j = 0; j < skus.length; j++) {
        // 根据当前sku是否参加活动,变更按钮状态
        if (setSkuCodes.indexOf(skus[j]._skuCode) > -1) {
            // 改变按钮状态
            joinActiviyBySKU(skus[j]._activityId, spuCode, skus[j]._skuCode);
        } else if (joinOtherActivitySkuCodes.indexOf(skus[j]._skuCode) <= -1) {
            cancelActiviyBySKU(skus[j]._activityId, spuCode, skus[j]._skuCode);
        }
    }
}

// 选中sku商品,并将skucode加入待确认队列
function selectedSkuCheckBox(skuCode) {
    if (!($("#sku-" + skuCode + "").prop('disabled') == true)) {
        $("#sku-" + skuCode + "").prop("checked", true);
    }
}

// 移除sku选中,移除待确认队列
function cancelSelectedSkuCheckBox(skuCode) {
    if ($("#sku-" + skuCode + "").is(':checked')) {
        $("#sku-" + skuCode + "").prop("checked", false);
    }
}

// ******子节点展示隐藏
function showHide(d) {
    // 遍历所有的sku数据
    var skus = selectSkusBySpu(d._spuCode);
    return ' <div class="level2-content">\n' + getChildHtml(d._spuCode) + '</div>';
}


// 搜索spu下的所有sku
function selectSkusBySpu(spuCode) {
    if (selectData.length > 0) {
        for (let i = 0; i < selectData.length; i++) {
            if (selectData[i]._spuCode == spuCode) {
                return selectData[i]._skus;
            }
        }
    }
    return [];
}

// 批量参加活动
function batchJoin() {
    if (selectedSkuCodes.length <= 0) {
        layer.msg("请选择商品!", {
            icon: 5,
            time: 3000
        });
        return;
    }
    // 1将所有的待确认队列,追加到设置队列
    // 2清空待确认队列
    // 3更改所有选中的按钮状态
    $("#example-select-all").prop("checked", false);
    if (selectData.length > 0) {
        for (let i = 0; i < selectData.length; i++) {
            const SPU = selectData[i];
            if ($("#spu-" + SPU._spuCode + "").is(':checked')) {
                joinActiviyBySPU(SPU._spuCode);
            }
            var skus = SPU._skus;
            if (skus.length > 0) {
                for (let j = 0; j < skus.length; j++) {
                    const SKU = skus[j];
                    if (selectedSkuCodes.indexOf(SKU._skuCode) > -1) {
                        joinActiviyBySKU(SKU._activityId, SPU._spuCode, SKU._skuCode);
                        deleteFromToBeConfirmSku(SKU._skuCode);
                    }
                }
            }
        }
    }
}

/****************************************************** setTable ***********************************************************/

var overNum = []; // 存在超卖
var setTablsDatas;
var setChecked = []; // 选中的数据

// 初始化设置商品表格
function initSetDataTable() {
    var dttable = $('#setProduct').dataTable(); // 初始化dataTable，清空上一个值
    if (dttable) {
        dttable.fnDestroy(); //还原初始化了的datatable
        dttable.fnClearTable(); //清空一下table
    }
    setTablsDatas = '';
    setTablsDatas = $("#setProduct").DataTable({
        "autoWidth": false,
        /*"order": [
            [1, "desc"]
        ],*/
        "ordering": false,
        "searching": false,
        "paging": true,
        "serverSide": false,
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": false,
        "aLengthMenu": [50],
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='./loading.gif' />"
        },
        "fnDrawCallback": function () {
            // 翻页函数
            renderSetCheckbox();
        },
        data: setSkuLists,
        "columns": [{
            "data": "_skuCode",
            "orderable": false,
            "className": "dt-body-center",
            "render": function (data, type, row) {
                return setChecked.indexOf(data) == -1 ? '<input id="sku-' + data + '" name="oneCheckbox"  onclick="setSkuCheckboxClick(\'' + data + '\')" type="checkbox" class="checkbox mr-5">' : '<input id="sku-' + data + '" name="oneCheckbox"  onclick="setSkuCheckboxClick(\'' + data + '\')" type="checkbox" checked class="checkbox mr-5">';
            }
        },
            {
                "data": "_spuCode",
                "type": "string"
            },
            {
                "data": "_spuName",
                "type": "string"
            },
            {
                "data": "_skuCode",
                "type": "string"
            },
            {
                "data": "_specifications",
                "type": "string"
            },
            {
                "data": "_unit",
                "type": "string"
            },
            {
                "data": "_costPrice"
            },

            {
                "data": "_tradePrice",
                render: function (data, type, row) {
                    var overNum = "";
                    if (row._stock <= 0) {
                        overNum = '<span style="font-size: 30%;color: red;display: block;clear: both;">存在超卖</span>'
                    }
                    var lessCost = "";
                    if (row._tradePrice <= row._costPrice) {
                        lessCost = '<span style="font-size: 30%;color: red;display: block;clear: both;">小于成本价</span>'
                    }
                    return data + overNum + lessCost;
                }
            },
            {
                "data": "_Prices"
            },
            {
                "data": "_skuCode",
                "type": "string",
                "render": function (data, type, row) {
                    return '<input type="button" id="cancel-' + data + '" onclick="cancelBySkU(\'' + row._activityId + '\',\'' + row._spuCode + '\',\'' + data + '\')" class="btn btn-secondary size-S radius" value="取消">'
                }
            }
        ]
    });
}

//每行折扣方式变化触发的函数
function setRuleType(value, skuCode) {
    // 改变样式,更新实际数据
    if (value == 10) {
        $("#ruleValue-" + skuCode).parent().html('<input id="ruleValue-' + skuCode + '" type="text" value="' + 0 + '"  onchange="ruleValueChange(this.value,\'' + skuCode + '\')"  class="f-l input-text w-50 ml-5 radius"><span class="f-l lh-26 pr-5 pl-5">折= </span>');
    } else {
        $("#ruleValue-" + skuCode).parent().html('<input id="ruleValue-' + skuCode + '" type="text" value="' + 0 + '"  onchange="ruleValueChange(this.value,\'' + skuCode + '\')" class="f-l input-text w-50 ml-5 radius"><span class="f-l lh-26 pr-5 pl-5">元= </span>');
    }
    $("#activityPrice-" + skuCode).val(0)
    for (let i = 0; i < setSkuLists.length; i++) {
        const element = setSkuLists[i];
        if (element._skuCode == skuCode) {
            element._ruleType = value;
            element._activity_price = 0;
        }
    }
}

// 单个sku折扣率变化事件
function ruleValueChange(value, skuCode) {
    // 变更活动价格
    var SKU = selectSKUFromSetSkuLists(skuCode);
    if (value == "") {
        $("#ruleValue-" + skuCode).val(SKU._ruleValue);
        return;
    }
    if (SKU._ruleType == 10) { //打折
        var price = Math.round((SKU._saleprices * (value / 10)) * 100) / 100;
        if (price < SKU._costPrice) {
            layer.confirm('商品设置后低于成本价，是否继续？', {
                btn: ['确定', '取消'] //按钮
            }, function (index) {
                for (let i = 0; i < setSkuLists.length; i++) {
                    const ele = setSkuLists[i];
                    if (ele._skuCode == skuCode) {
                        ele._ruleValue = value;
                        ele._activity_price = price;
                    }
                }
                insertIntoLseeCost(skuCode);
                $("#activityPrice-" + skuCode).val(price);
                // 提示低于成本价
                tipLessCost();
                layer.close(index);
            }, function (index) {
                $("#ruleValue-" + skuCode).val(SKU._ruleValue);
                $("#activityPrice-" + skuCode).val(SKU._activity_price);
            });
        } else {
            for (let i = 0; i < setSkuLists.length; i++) {
                const ele = setSkuLists[i];
                if (ele._skuCode == skuCode) {
                    ele._ruleValue = value;
                    ele._activity_price = price;
                }
            }
            deleteFromLessCost(skuCode);
            $("#activityPrice-" + skuCode).val(price)
        }
    } else {
        var price = Math.round((SKU._saleprices - value) * 100) / 100;
        if (price <= 0) {
            layer.msg("商品减价后价格小于0的商品无法操作", {
                icon: 5,
                time: 3000
            });
            $("#ruleValue-" + skuCode).val(SKU._ruleValue)
            $("#activityPrice-" + skuCode).val(SKU._activity_price);
            return;
        } else {
            if (price < SKU._costPrice) {
                layer.confirm('商品设置后低于成本价，是否继续？', {
                    btn: ['确定', '取消'] //按钮
                }, function (index) {
                    for (let i = 0; i < setSkuLists.length; i++) {
                        const ele = setSkuLists[i];
                        if (ele._skuCode == skuCode) {
                            ele._ruleValue = value;
                            ele._activity_price = price;
                        }
                    }
                    insertIntoLseeCost(skuCode);
                    $("#activityPrice-" + skuCode).val(price);
                    layer.close(index);
                }, function (index) {
                    $("#ruleValue-" + skuCode).val(SKU._ruleValue)
                    $("#activityPrice-" + skuCode).val(SKU._activity_price);
                });
            } else {
                for (let i = 0; i < setSkuLists.length; i++) {
                    const ele = setSkuLists[i];
                    if (ele._skuCode == skuCode) {
                        ele._ruleValue = value;
                        ele._activity_price = price;
                    }
                }
                deleteFromLessCost(skuCode);
                $("#activityPrice-" + skuCode).val(price)
            }
        }
    }
}

// 活动价变化时,反推折扣或减价金额
function activityPriceChange(value, skuCode) {
    var SKU = selectSKUFromSetSkuLists(skuCode);
    if (value == "") {
        $("#activityPrice-" + skuCode).val(SKU._activity_price);
        return;
    }
    if (value < SKU._costPrice) {
        layer.confirm('商品设置后低于成本价，是否继续？', {
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            // 反推
            var ruleValue;
            if (SKU._ruleType == 10) {
                ruleValue = Math.round(((SKU._activity_price / value) * 10) * 100) / 100;
            } else {
                ruleValue = Math.round((SKU._activity_price - value) * 100) / 100;
            }
            for (let i = 0; i < setSkuLists.length; i++) {
                const ele = setSkuLists[i];
                if (ele._skuCode == skuCode) {
                    ele._ruleValue = ruleValue;
                    ele._activity_price = value;
                }
            }
            insertIntoLseeCost(skuCode);
            $("#ruleValue-" + skuCode).val(ruleValue);
            layer.close(index);
        }, function (index) {
            $("#activityPrice-" + skuCode).val(SKU._activity_price);
        });
    } else {
        // 反推
        var ruleValue;
        if (SKU._ruleType == 10) {
            ruleValue = Math.round(((SKU._activity_price / value) * 10) * 100) / 100;
        } else {
            ruleValue = Math.round((SKU._activity_price - value) * 100) / 100;
        }
        for (let i = 0; i < setSkuLists.length; i++) {
            const ele = setSkuLists[i];
            if (ele._skuCode == skuCode) {
                ele._ruleValue = ruleValue;
                ele._activity_price = value;
            }
        }
        deleteFromLessCost(skuCode);
        $("#ruleValue-" + skuCode).val(ruleValue);
    }
}

// 单个商品设置限购数量变化事件
function limitNumChange(value, skuCode) {
    var SKU = selectSKUFromSetSkuLists(skuCode);
    if (value == "") {
        $("#limitNum-" + skuCode).val(SKU._limit_num);
        return;
    }
    if (value > SKU._stock) {
        layer.confirm('商品设置后有超卖库存，是否继续？', {
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            //更新库存数据
            for (let i = 0; i < setSkuLists.length; i++) {
                const ele = setSkuLists[i];
                if (ele._skuCode == skuCode) {
                    ele._limit_num = value;
                }
            }
            insertIntoOverNum(skuCode);
            tipOverNum();
            layer.close(index);
        }, function (index) {
            $("#limitNum-" + skuCode).val(value);
        });
    } else {
        //更新库存数据
        for (let i = 0; i < setSkuLists.length; i++) {
            const ele = setSkuLists[i];
            if (ele._skuCode == skuCode) {
                ele._limit_num = value;
            }
        }
        deleteFromOverNum(skuCode);
        tipOverNum();
    }
}

// 重新渲染设置商品页面的ckeckbox 按钮
function renderSetCheckbox() {
    changeAllCheckbox(false);
    if (setChecked.length > 0) {
        var checked = true;
        let nowPage = getNowPage();
        if (nowPage != null) {
            for (let i = 0; i < nowPage.length; i++) {
                const element = nowPage[i];
                if (setChecked.indexOf(element._skuCode) <= -1) {
                    checked = false;
                    break;
                }
            }
            changeAllCheckbox(checked);
        }
    }
    // 提示低于成本价
    tipOverNum();
}

// 单个sku checkbox点击书简
function setSkuCheckboxClick(skuCode) {
    if ($("#sku-" + skuCode).is(":checked")) {
        insertTosetChecked(skuCode);
    } else {
        deleteFromsetChecked(skuCode)
    }
}

// 取消参加
function cancelBySkU(activityId, spuCode, skuCode) {
    layer.confirm('确定要取消吗？', {
        btn: ['确定', '取消'] //按钮
    }, function (index) {
        var sku = selectSKUFromSetSkuLists(skuCode);
        if (sku._id != null && sku._id > 0) {
            var ids = [];
            ids.push(sku._id);
            cancelFromDB(ids);
        }
        // 移除本次已参加的队列
        cancelActiviyBySKU(activityId, spuCode, skuCode);
        // 从setCkecked 移除
        deleteFromsetChecked(skuCode);
        // 重新加载table
        initSetDataTable();
        layer.close(index);
    }, function (index) {
        layer.close(index);
    });
}

// 发送http请求取消参加活动
function cancelFromDB(ids) {
    if (ids.length > 0) {
        $.ajax({
            url: root.promotion.cancel_product_by_id,
            cache: false, //禁用缓存
            contentType: 'application/json',
            type: "PUT",
            data: JSON.stringify(ids),
            success: function (data) {
                if (data.errorCode == 0) {
                    layer.msg('取消成功', {
                        icon: 1,
                        time: 2000
                    });
                    searchProduct();
                    $("#promotion_manage").submit();
                } else {
                    layer.msg(data.sub_msg, {
                        icon: 2,
                        time: 2000
                    });
                }
            },
            error: function () {
                console.log("!!!!取消失败,促销后台异常!!!!");
                layer.msg('取消失败,促销后台异常', {
                    icon: 2,
                    time: 2000
                });
            }
        });
    }
}

//全部满减
function allReduce() {
    var reduce = $("#allReduce").val();
    if (reduce == "" || reduce == 0) {
        layer.msg("请设置金额..", {
            icon: 5,
            time: 3000
        });
        return;
    }
    // 初始化超卖列表
    lessCost = [];
    // 清空打折数据
    $("#allDiscount").val("");
    // 计算金额,重新渲染表格
    if (setSkuLists.length > 0) {
        var isAsk = false;
        for (let i = 0; i < setSkuLists.length; i++) {
            const SKU = setSkuLists[i];
            SKU._ruleType = 20;
            SKU._ruleValue = reduce;
            // 计算价格后小于0的商品
            var price = Math.round((SKU._saleprices - reduce) * 100) / 100;
            if (price <= 0) {
                layer.msg("存在减价后价格小于0的商品无法提交", {
                    icon: 5,
                    time: 3000
                });
                setSkuLists = setSkuLists_copy;
                return;
            }
            // 计算金额(小于成本价提示)
            if (SKU._costPrice > price) {
                if (!isAsk) {
                    isAsk = true;
                }
                insertIntoLseeCost(SKU._skuCode);
            }
            // 设置促销价
            SKU._activity_price = price;
        }
    }
}


// 提示超卖
function tipOverNum() {
    for (let i = 0; i < setSkuCodes.length; i++) {
        const skuCode = setSkuCodes[i];
        if (overNum.indexOf(skuCode) <= -1) {
            $("#tipOverNum-" + skuCode).hide();
        } else {
            $("#tipOverNum-" + skuCode).show();
        }
    }
}

//全部设置数量
function allSetNum() {
    setSkuLists_copy = setSkuLists;
    var num = $("#allSetNum").val();
    if (num == "" || num == 0) {
        layer.msg("请设置数量..", {
            icon: 5,
            time: 3000
        });
        return;
    }
    overNum = [];
    // 设置数量
    if (setSkuLists.length > 0) {
        var isAsk = false;
        for (let i = 0; i < setSkuLists.length; i++) {
            const SKU = setSkuLists[i];
            // 设置数量`
            SKU._limit_num = num;
            // 计算超卖
            if (SKU._stock - num < 0) {
                if (!isAsk) {
                    isAsk = true;
                }
                insertIntoOverNum(SKU._skuCode);
            }
        }
        askConfirmOverNum(isAsk);
    }
}

// 询问超卖
function askConfirmOverNum(isAsk) {
    if (isAsk) {
        layer.confirm('存在部分商品设置后有超卖库存，是否继续？', {
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            // 重新加载table
            initSetDataTable();
            // 提示低于成本价
            tipOverNum();
            layer.close(index);
        }, function (index) {
            setSkuLists = setSkuLists_copy;
        });
    } else {
        // 重新加载table
        initSetDataTable();
        // 提示低于成本价
        tipOverNum();
    }
}

// 批量取消
function cancelChecked() {
    console.log(setChecked)
    if (setChecked.length > 0) {
        layer.confirm('确认取消选中商品吗？', {
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            console.log("取消前list== " + setSkuLists.length);
            console.log("取消前== " + setSkuCodes.length);

            var ids = [];
            for (let i = 0; i < setSkuLists.length; i++) {
                const checkedElement = setSkuLists[i];
                if (checkedElement._id != null && checkedElement._id > 0 && ids.indexOf(checkedElement._id) <= -1 && setChecked.indexOf(checkedElement._skuCode)>=0) {
                    ids.push(checkedElement._id);
                }
            }

            // 取消所有选中的数据
            for (let i = 0; i < setChecked.length; i++) {
                var SKU = selectSKUFromSetSkuLists(setChecked[i]);
                deleteFromSetSku(SKU._spuCode, SKU._skuCode);
                deleteFromSetSpu(SKU._spuCode);
            }
            for (let i = 0; i < setChecked.length; i++) {
                deleteFromSetSkuLists(setChecked[i]);
            }
            cancelFromDB(ids);
            setChecked = [];
            // 重新加载表数据
            initSetDataTable();
            console.log("取消后list== " + setSkuLists.length);
            console.log("取消后== " + setSkuCodes.length);
            layer.close(index);
        }, function (index) {
        });
    } else {
        layer.msg('请选中要取消的商品!', {
            icon: 2,
            time: 2000
        });
    }
}

// 全部取消
function cancelAll() {
    if (setSkuLists.length > 0) {
        layer.confirm('确认取消全部商品吗？', {
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            /*  // 清空数据
              setSpuCodes = []; // 已经参加本次活动的spuCode集合
              setSkuCodes = []; // 已经参加本次活动的skuCode集合
              setSkuLists = []; // 已经参加本次活动的sku集合
              setSkuLists_copy = [];

              // 发送后台请求
              var ids = [];
              for (let i = 0; i < setSkuLists.length; i++) {
                  const checkedElement = setSkuLists[i];
                  ids.push(checkedElement._id);
              }
              cancelFromDB(ids);
              // 重新加载table
              initSetDataTable();
              layer.close(index);*/

            // 发送后台请求
            var ids = [];
            for (let i = setSkuLists.length - 1; i >= 0; i--) {
                const checkedElement = setSkuLists[i];
                if (checkedElement._id > 0) {
                    ids.push(checkedElement._id);
                }
                // 移除本次已参加的队列
                cancelActiviyBySKU(checkedElement._activityId, checkedElement._spuCode, checkedElement._skuCode);
                // 从setCkecked 移除
                deleteFromsetChecked(checkedElement._skuCode);
            }
            cancelFromDB(ids);
            // 重新加载table
            initSetDataTable();
            layer.close(index);
        }, function (index) {
        });
    }
}


// 全选checkbox
function checkedAll() {
    var startAndEnd = getNowPage();
    for (let index = 0; index < startAndEnd.length; index++) {
        var checked = $("#pitchAll").is(':checked');
        changeSetCheckbox(startAndEnd[index]._skuCode, checked);
        if (checked) {
            insertTosetChecked(startAndEnd[index]._skuCode);
        } else {
            deleteFromsetChecked(startAndEnd[index]._skuCode);
        }
    }
}

// 获取当前页的开始和结束索引
function getNowPage() {
    // 选中本页全部sku
    if (setTablsDatas) {
        var page = setTablsDatas.page();
        var start = page * 50;
        var end = (page + 1) * 50;
        var count = setSkuLists.length;
        if (end > count) {
            end = count;
        }
        return setSkuLists.slice(start, end);
    }
    return null;
}

// 选中单个sku的checkbox 只改变状态
function changeSetCheckbox(skuCode, checked) {
    $("#sku-" + skuCode).prop("checked", checked);
}

// 选中或取消全选checkbox
function changeAllCheckbox(checked) {
    $("#pitchAll").prop("checked", checked);
}

//****************************************************************数组操作***********************************************
// 根据spuCode获取活动id, 一部分参加活动,一部分为参加活动返回 0(参加活动), skucode参加两个不同的活动返回 -1(已参加), skucode全部参加同一个活动返回活动id (参加其他活动)
function getActivityBySpuCode(spuCode) {
    if (selectData.length > 0) {
        for (let i = 0; i < selectData.length; i++) {
            if (selectData[i]._spuCode == spuCode) {
                return selectData[i]._activityId;
            }
        }
    }
    return 0;
}

function insertIntoOverNum(skuCode) {
    if (overNum.indexOf(skuCode) <= -1) {
        overNum.push(skuCode);
    }
}

function deleteFromOverNum(skuCode) {
    if (overNum.indexOf(skuCode) > -1) {
        overNum.splice(overNum.indexOf(skuCode), 1);
    }
}

// ********新增到待确认队列 sku级别
function insertToToBeConfirmSku(skuCode) {
    // 如果本商品没有参加其他活动
    if (joinOtherActivitySkuCodes.indexOf(skuCode) <= -1) {
        //且未参加本次活动
        if (setSkuCodes.indexOf(skuCode) <= -1) {
            var index = selectedSkuCodes.indexOf(skuCode);
            if (index <= -1) {
                selectedSkuCodes.push(skuCode);
            }
        }
    }
}

// 从待确认队列移除
function deleteFromToBeConfirmSku(skuCode) {
    var index = selectedSkuCodes.indexOf(skuCode);
    if (index > -1) {
        selectedSkuCodes.splice(index, 1);
    }
}

// ********新增到待确认队列 spu级别
function insertToToBeConfirmSpu(spuCode) {
    // 如果本商品没有参加其他活动
    if (selectedSpuCodes.indexOf(spuCode) <= -1) {
        selectedSpuCodes.push(spuCode);
    }
}

// ********移除待确认队列 spu级别
function deleteFromToBeConfirmSpu(spuCode) {
    // 如果本商品没有参加其他活动
    if (selectedSpuCodes.indexOf(spuCode) > -1) {
        selectedSpuCodes.splice(selectedSpuCodes.indexOf(spuCode), 1);
    }
}

// *********新增到参加活动队列 sku级别
function insertToSetSku(spuCode, skuCode) {
    // 如果本商品没有参加其他活动
    if (joinOtherActivitySkuCodes.indexOf(skuCode) <= -1) {
        // 如果此商品在待确认队列,移除
        if (selectedSkuCodes.indexOf(skuCode) > -1) {
            selectedSkuCodes.splice(selectedSkuCodes.indexOf(skuCode), 1);
        }
        //添加到活动队列
        if (setSkuCodes.indexOf(skuCode) <= -1) {
            setSkuCodes.push(skuCode);
        }
        var skus = selectSkusBySpu(spuCode);
        for (let i = 0; i < skus.length; i++) {
            if (skus[i]._skuCode == skuCode) {
                insertToSetSkuLists(skus[i]);
                break;
            }
        }
    }
}

// 新增 设置商品 setlist
function insertToSetSkuLists(SKU) {
    if (setSkuLists.length > 0) {
        var isNotExit = true;
        for (let i = 0; i < setSkuLists.length; i++) {
            const skuList = setSkuLists[i];
            if (skuList._skuCode == SKU._skuCode) {
                isNotExit = false;
                break;
            }
        }
        if (isNotExit) {
            setSkuLists.push(SKU);
        }
    } else {
        setSkuLists.push(SKU);
    }
}


// 从活动队列移除 sku级别
function deleteFromSetSku(spuCode, skuCode) {
    if (setSkuCodes.indexOf(skuCode) > -1) {
        setSkuCodes.splice(setSkuCodes.indexOf(skuCode), 1);
    }
    deleteFromSetSkuLists(skuCode);
}

// *********新增到参加活动队列 spu级别
function insertToSetSpu(spuCode) {
    if (setSpuCodes.indexOf(spuCode) <= -1) {
        setSpuCodes.push(spuCode);
    }
}

// 从活动队列移除 spu级别
function deleteFromSetSpu(spuCode) {
    if (setSpuCodes.indexOf(spuCode) > -1) {
        setSpuCodes.splice(setSpuCodes.indexOf(spuCode), 1);
    }
}

// ******* 展开队列 添加
function insertToSelectSpuOpen(spuCode) {
    if (selectSpuOpen.indexOf(spuCode) <= -1) {
        selectSpuOpen.push(spuCode);
    }
}

// 移除 展开队列
function deleteFromSelectSpuOpen(spuCode) {
    if (selectSpuOpen.indexOf(spuCode) > -1) {
        selectSpuOpen.splice(selectSpuOpen.indexOf(spuCode), 1);
    }
}

// 移除 设置商品 setlist
function deleteFromSetSkuLists(skuCode) {
    if (setSkuLists.length > 0) {
        for (let index = 0; index < setSkuLists.length; index++) {
            const element = setSkuLists[index];
            if (element._skuCode == skuCode) {
                setSkuLists.splice(setSkuLists.indexOf(element), 1);
            }
        }
    }
}

// 移除 设置商品 setlist
function selectSKUFromSetSkuLists(skuCode) {
    if (setSkuLists.length > 0) {
        for (let index = 0; index < setSkuLists.length; index++) {
            const element = setSkuLists[index];
            if (element._skuCode == skuCode) {
                return element;
            }
        }
    }
}

// 新增到设置商品选中队列
function insertTosetChecked(skuCode) {
    if (setChecked.indexOf(skuCode) <= -1) {
        setChecked.push(skuCode);
    }
}

// 从商品选中队列移除
function deleteFromsetChecked(skuCode) {
    if (setChecked.indexOf(skuCode) > -1) {
        setChecked.splice(setChecked.indexOf(skuCode), 1);
    }
}

//**************************************样式相关***************************
//鼠标经过单个sku已参加显示取消参加按钮
function onSkuJoinShow(ev) {
    $(ev).next().show();
    $(ev).hide();
}

//鼠标离开单个sku取消参加按钮显示已参加
function onSkucancelShow(ev) {
    $(ev).prev().show();
    $(ev).hide();
}

/********************************excel导入***************************************/
// 导入文件点击事件
function askImport() {
    if ($("#activityPerson").val().trim() == "" || $("#activityLocation").val().trim() == "" || $("#startTime").val().trim() == "") {
        var msg = "请先选择";
        msg += $("#activityPerson").val().trim() == "" ? "[活动对象] " : "";
        msg += $("#activityLocation").val().trim() == "" ? "  [活动区域]" : "";
        msg += $("#startTime").val().trim() == "" ? "  [开始时间]" : "";
        layer.msg(msg, {
            icon: 5,
            time: 3000
        });
        return;
    }
    $("#file").show();
    $("#fileButton").show();
}

// excel文件变化事件
function changeExcel() {
    var fileDir = $("#file").val();
    var suffix = fileDir.substr(fileDir.lastIndexOf("."));
    if ("" == fileDir) {
        layer.msg("请选择excel文件", {
            icon: 2,
            time: 3000
        });
        return;
    }
    if (".xls" != suffix && ".xlsx" != suffix) {
        layer.msg("格式错误", {
            icon: 2,
            time: 3000
        });
        $('#file').val("");
    }
}

// 开始上传
function importExcel() {
    if ($("#activityPerson").val().trim() == "" || $("#activityLocation").val().trim() == "" || $("#startTime").val().trim() == "") {
        var msg = "请先选择";
        msg += $("#activityPerson").val().trim() == "" ? "[活动对象] " : "";
        msg += $("#activityLocation").val().trim() == "" ? "  [活动区域]" : "";
        msg += $("#startTime").val().trim() == "" ? "  [开始时间]" : "";
        layer.msg(msg, {
            icon: 5,
            time: 3000
        });
        return;
    } else {
        var fileDir = $("#file").val();
        var suffix = fileDir.substr(fileDir.lastIndexOf("."));
        if ("" == fileDir) {
            layer.msg("请选择excel文件", {
                icon: 2,
                time: 3000
            });
            return;
        } else {
            var formData = new FormData();
            formData.append("file", $("#file")[0].files[0]);
            formData.append("activityPerson", $("#activityPerson").val());
            formData.append("activityLocation", $("#activityLocation").val());
            formData.append("activityProductList", JSON.stringify(convertSkuList()));
            formData.append("activityStartTime", $("#startTime").val());
            formData.append("activityEndTime", $("#endTime").val());
            $.ajax({
                url: root.promotion.import_reduce_product,
                cache: false,  //禁用缓存
                type: "POST",
                // 告诉jQuery不要去处理发送的数据
                processData: false,
                // 告诉jQuery不要去设置Content-Type请求头
                contentType: false,
                data: formData,
                success: function (data) {
                    console.log(data)
                    if (data.errorCode == 0) {
                        layer.msg("excel上传成功!", {icon: 6, time: 3000});
                        // 处理导入的数据 setSkuList setSkus setSpus 重新加载表数据
                        //var skuList = converExcelToSkus(data.data);
                        console.log(data.data);
                        fillTable(converExcelToSkus(data.data));
                        setP();
                    } else {
                        layer.alert(data.sub_msg, {icon: 2});
                    }
                }
            });
        }
    }
}

/************************************满减区域***********************************/
// 优惠方式变化事件
$("#addOneTr").attr("disabled", true);

function fixGradeClick(value) {
    $("#form-member").valid();
    if (value == 10) {
        $("#addOneTr").attr("disabled", true);
    } else {
        $("#addOneTr").attr("disabled", false);

    }
}

$("#fixGrade-10").prop("checked", true);
$("#useCondition-20").hide();
$("#fullReductionWay_unit-20").hide();
// 满减类型变化事件
$("#fullReductionWay").change(function () {
    changeFullReductionWay();
});

// 重置table
function changeFullReductionWay() {
    // 满减方式变化事件
    var fullReductionWay = $("#fullReductionWay").val();
    if (fullReductionWay == 10) {
        $("#fixGrade-10-span").html("每满固定金额进行优惠");
        $("#fixGrade-20-span").html("满不同级的固定金额进行优惠（最多可设置5层级）");
        $("#useCondition-10").show();
        $("#fullReductionWay_unit-10").show();
        $("#useCondition-20").hide();
        $("#fullReductionWay_unit-20").hide();
        // 替换table level
        for (let i = 0; i < rowNum; i++) {
            var index = i + 1;
            $("#useCondition-20-" + index).parent().html('满<input type="text" onchange="reduce(this)" class="input-text w-80 mr-10 ml-10 radius" id="useCondition-10-' + index + '" name="useCondition-10-' + index + '" >元')
        }
        // 清空数据
        $("#useCondition-10").val("");
        $("#useCondition-20").val("");
        $("#ruleValue-10").val("");
        $("#ruleValue-20").val("");
        $("#preferentialMost").val(0);
        $("#roleValue-count-1").val("");
        $("#roleValue-reduce-1").val("");
    } else {
        $("#fixGrade-10-span").html("每满固定数量进行优惠");
        $("#fixGrade-20-span").html("满不同级的固定数量进行优惠（最多可设置5层级）");
        $("#useCondition-10").hide();
        $("#fullReductionWay_unit-10").hide();
        $("#useCondition-20").show();
        $("#fullReductionWay_unit-20").show();
        // 替换table level
        for (let i = 0; i < rowNum; i++) {
            var index = i + 1;
            $("#useCondition-10-" + index).parent().html('满<input type="text" onchange="reduce(this)" class="input-text w-80 mr-10 ml-10 radius" id="useCondition-20-' + index + '" id="useCondition-20-' + index + '"  >件');
        }
        // 清空数据
        $("#useCondition-10").val("");
        $("#useCondition-20").val("");
        $("#ruleValue-10").val("");
        $("#ruleValue-20").val("");
        $("#preferentialMost").val(0);
        $("#roleValue-count-1").val("");
        $("#roleValue-reduce-1").val("");
    }
    if (rowNum > 1) {
        for (let i = 0; i < rowNum - 1; i++) {
            $("#reduceLevel tr:last").remove();
        }
        rowNum = 1;
    }
    // 重置满减区域
}


// 改变所有优惠方式
function changeAllReductionWay() {
    // 满减方式变化事件
    var fullReductionWay = $("#fullReductionWay").val();
    if (fullReductionWay == 10) {
        $("#useCondition-10").show();
        $("#fullReductionWay_unit-10").show();
        $("#useCondition-20").hide();
        $("#fullReductionWay_unit-20").hide();
        // 替换table level
        for (let i = 0; i < rowNum; i++) {
            var index = i + 1;
            $("#useCondition-20-" + index).parent().html('满<input type="text" onchange="reduce(this)" class="input-text w-80 mr-10 ml-10 radius" id="useCondition-10-' + index + '" name="useCondition-10-' + index + '" >元')
        }
    } else {
        $("#useCondition-10").hide();
        $("#fullReductionWay_unit-10").hide();
        $("#useCondition-20").show();
        $("#fullReductionWay_unit-20").show();
        // 替换table level
        for (let i = 0; i < rowNum; i++) {
            var index = i + 1;
            $("#useCondition-10-" + index).parent().html('满<input type="text" onchange="reduce(this)" class="input-text w-80 mr-10 ml-10 radius" id="useCondition-20-' + index + '" id="useCondition-20-' + index + '"  >件');
        }
    }
}

// 折扣方式变化事件
$("#ruleType-10").prop("checked", true);
$("#ruleValue-20").attr("disabled", true);

// 满减类型变化事件
function ruleTypeChange() {
    $("#form-member").valid();
    var val = $('input[name="ruleType"]:checked').val();
    if (val == 10) {
        $("#ruleType-20").prop("checked", false);
        $("#ruleType-10").prop("checked", true);

        $("#ruleValue-20").attr("disabled", true);
        $("#ruleValue-10").attr("disabled", false);
    } else {
        $("#ruleType-20").prop("checked", true);
        $("#ruleType-10").prop("checked", false);
        $("#ruleValue-20").attr("disabled", false);
        $("#ruleValue-10").attr("disabled", true);
    }
}

$.validator.addMethod("requiredRuleType10", function (value, element) {
    if (!$("#fixGrade-10").is(":checked") || !$("#ruleType-10").is(":checked") || value != "") {
        return true;
    }
    return false;
}, "不能为空");

$.validator.addMethod("requiredRuleType20", function (value, element) {
    if (!$("#fixGrade-10").is(":checked") || !$("#ruleType-20").is(":checked") || value != "") {
        return true;
    }
    return false;
}, "不能为空");

$.validator.addMethod("requiredPreferentialMost", function (value, element) {
    if (!$("#fixGrade-10").is(":checked") || $("#ispreferentialMost").is(':checked') || value != "") {
        return true;
    }
    return false;
}, "不能为空");
$.validator.addMethod("requiredUseCondition10", function (value, element) {
    if (!$("#fixGrade-10").is(":checked") || value != "") {
        return true;
    }
    return false;
}, "不能为空");
$.validator.addMethod("requiredUseCondition101", function (value, element) {
    if (!$("#fixGrade-20").is(":checked") || value != "") {
        return true;
    }
    return false;
}, "不能为空");
$.validator.addMethod("requiredRoleValueCount1", function (value, element) {
    if (!$("#fixGrade-20").is(":checked") || value != "" || !$("#ruleType-count-1").is(':checked')) {
        return true;
    }
    return false;
}, "不能为空");

$.validator.addMethod("requiredRoleValueReduce1", function (value, element) {
    if (!$("#fixGrade-20").is(":checked") || value != "" || !$("#ruleType-reduce-1").is(':checked')) {
        return true;
    }
    return false;
}, "不能为空");


//上不封顶ckeckbox改变事件
$("#preferentialMost").val(0);


function ispreferentialMostChange(obj) {
    if ($(obj).is(':checked')) {
        $("#preferentialMost_show").css('display', 'none');
        $("#preferentialMost").val(0);
    } else {
        $("#preferentialMost_show").css('display', 'inline');
        $("#preferentialMost").val("");
    }
}

// 满减金额限制输入
function reduce(obj) {
    //obj.value = obj.value.replace(/\b(0+)/gi, ""); // 替换开头的0
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (obj.value != "" && obj.value < 0) {
        obj.value = 0;
    }
}

// 多层级关联输入限制
function levelReduce(obj, index) {
    var type = $("#fullReductionWay").val();
    // 获取上一层级的输入值
    var id = '#useCondition-' + $("#fullReductionWay").val() + '-' + (index - 1);
    var preValue = $(id).val();
    if (Number(obj.value) <= Number(preValue)) {
        if (type == 10) {
            layer.msg('必须大于上一级别的门槛金额', {
                icon: 2,
                time: 3000
            });
        } else {
            layer.msg('必须大于上一级别的数量', {
                icon: 2,
                time: 3000
            });
        }
        obj.value = "";
    }
    obj.value = obj.value.replace(/\b(0+)/gi, ""); // 替换开头的0
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (obj.value != "" && obj.value < 1) {
        obj.value = 1;
    }
}

// 折扣限制输入
function discount(obj) {
    //obj.value = obj.value.replace(/\b(0+)/gi, ""); // 替换开头的0
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (obj.value > 10) {
        obj.value = 10;
    }
    if (obj.value != "" && obj.value < 1) {
        obj.value = 1;
    }
}


// 当前表格的行数
var rowNum = 1;

// 新增一行函数
function addTr() {
    if (rowNum == 10) {
        layer.msg('超出最大级别!', {
            icon: 2,
            time: 3000
        });
        return;
    }
    //如果上一级没有填写,则不允许创建
    var id = '#useCondition-' + $("#fullReductionWay").val() + '-' + rowNum;
    if ($(id).val() == "" || $(id).val() == 0) {
        layer.msg('请先补全本级数据!', {
            icon: 2,
            time: 3000
        });
        return;
    }
    $("#deleteLevel-" + rowNum).hide();
    // 获取最后一行的优惠方式
    var name = "promotion-" + rowNum;
    var val = $('input[name=' + name + ']:checked').val();
    console.log(val);
    rowNum += 1;
    // 隐藏上一级的删除按钮
    var table = $("#reduceLevel");
    var td2 = "";
    if ($("#fullReductionWay").val() == 10) {
        td2 = '满<input type="text" onchange="levelReduce(this,' + rowNum + ')" class="input-text w-80 mr-10 ml-10 radius" id="useCondition-10-' + rowNum + '" name="useCondition-10-' + rowNum + '">元';
    } else {
        td2 = '满<input type="text" onchange="levelReduce(this,' + rowNum + ')" class="input-text w-80 mr-10 ml-10 radius" id="useCondition-20-' + rowNum + '" name="useCondition-20-' + rowNum + '">件';
    }
    table.append('<tr>\n' +
        '       <td>' + rowNum + '</td>\n' +
        '       <td>' + td2 + '</td>\n' +
        '       <td>\n' +
        '           <input type="radio" class="radio " id="ruleType-count-' + rowNum + '" name="promotion-' + rowNum + '" value="10" onclick="levelRoleTypeClick(this.value)">打折\n' +
        '           <input type="text" class="input-text w-60 radius ml-5" id="roleValue-count-' + rowNum + '"  name="roleValue-count-' + rowNum + '" onchange="discount(this)">\n' +
        '           <span class="pl-5">折</span>\n' +
        '           <input type="radio" class="radio ml-20" id="ruleType-reduce-' + rowNum + '"  name="promotion-' + rowNum + '" value="20" onclick="levelRoleTypeClick(this.value)">减现金\n' +
        '           <input type="text" class="input-text w-60 radius ml-5"  id="roleValue-reduce-' + rowNum + '" name="roleValue-reduce-' + rowNum + '" onchange="reduce(this)">\n' +
        '           <span class="pl-5">元</span>\n' +
        '       </td>\n' +
        '       <td><a href="javascript:void(0)" id="deleteLevel-' + rowNum + '" onclick="delTr()">删除</a></td>\n' +
        '   </tr>');
    if (val) {
        levelRoleTypeClick(val);
    }
}

// 删除一行
function delTr() {
    // 显示上衣行的删除按钮
    rowNum -= 1;
    $("#deleteLevel-" + rowNum).show();
    // 删除本行数据
    var table = $("#reduceLevel");
    $("#reduceLevel tr:last").remove();
}

// table中优惠方式变化事件
function levelRoleTypeClick(value) {
    //validateForm.resetForm();
    for (let i = 0; i < rowNum; i++) {
        var index = i + 1;
        if (value == 10) {
            $("#ruleType-count-" + index).prop("checked", true);
            $("#roleValue-reduce-" + index).val("");
        } else {
            $("#ruleType-reduce-" + index).prop("checked", true);
            $("#roleValue-count-" + index).val("");
        }
    }
    $("#form-member").valid();
}

/*******************************表单提交***************************************/

// 新增或修改
function addReduceActivity() {
    if (validateTable()) {
        saveData();
    }
}

// 入库,新增或更新
function saveData() {
    var loader = layer.load(0, {
        shade: [0.8, '#070002'] //0.1透明度的白色背景
    });
    var url = root.promotion.add_single_activity;
    var type = "POST";
    $.ajax({
        url: url,
        cache: false, //禁用缓存
        contentType: 'application/json; charset=UTF-8',
        type: type,
        data: JSON.stringify(convertSkuListToReduce(crmCustomerIdOnearry)),
        success: function (data) {
            if (data.errorCode == 0) {
                layer.msg("保存成功!", {
                    icon: 6,
                    time: 3000
                });
                // 关闭页面
                setTimeout(function () {
                    layer.close(loader);
                    removeIframe();
                }, 3000);
                if (parent.activityId > 0) {
                    parent.reloadTable();
                }
            } else {
                layer.msg(data.sub_msg, {
                    icon: 2,
                    time: 3000
                });
                setTimeout(function () {
                    layer.close(loader);
                }, 3000);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
            console.log(textStatus);
            console.log(errorThrown);
            console.log("!!!!保存促销货送异常-促销后台!!!!");
            layer.msg('保存促销货送异常-促销后台', {
                icon: 2,
                time: 3000
            });
            setTimeout(function () {
                layer.close(loader);
            }, 3000);
        }
    });
}

// 提交前校验table
function validateTable() {
    if (setSkuLists.length <= 0) {
        layer.msg('请选择促销商品!', {
            icon: 2,
            time: 3000
        });
        return false;
    }
    for (let i = 0; i < setSkuLists.length; i++) {
        const skuList = setSkuLists[i];
        // 判断低于成本价
        if (skuList._tradePrice < skuList._costPrice) {
            layer.open({
                title: '提示',
                type: 1,
                shift: 7,
                shadeClose: false,
                content: ' <div class="f-l w-300 lh-300 text-c ml-30 pb-15">\n' +
                    '                    <h5><b>部分商品低于成本价，确认请输入密码</b></h5>\n' +
                    '                    <p class="mt-20"><input type="password" id="rePassword" class="input-text w-250 radius" placeholder="请输入密码"></p>\n' +
                    '                    <input class="btn btn-secondary radius size-L" type="button" onclick="reValidatePassword()" value="确&nbsp;&nbsp;&nbsp;&nbsp;认">  <input class="btn size-L radius ml-10" onclick="cancelValidatePassword()"  type="button"  value="取&nbsp;&nbsp;&nbsp;&nbsp;消">' +
                    '                </div>'
            });
            return false;
        }
    }
    return true;
}

// 校验密码确认按钮
function reValidatePassword() {
    if ($("#rePassword").val().trim() == "") {
        layer.msg('请输入密码!', {
            icon: 2,
            time: 3000
        });
    } else {
        $.ajax({
            url: root.promotion.check_edit_price_password,
            cache: false, //禁用缓存
            contentType: 'application/x-www-form-urlencoded',
            type: "POST",
            data: {"password": $("#rePassword").val()},
            success: function (data) {
                if (data.result == 10) {
                    saveData();
                    layer.closeAll();
                } else {
                    layer.msg(data.msg, {
                        icon: 2,
                        time: 3000
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);
                console.log("!!!!密码校验服务异常!!!!");
                layer.msg('密码校验服务异常', {
                    icon: 2,
                    time: 3000
                });
                layer.closeAll();
            }
        });
    }
}

// 校验密码取消按钮
function cancelValidatePassword() {
    layer.closeAll();
}

/*关闭详情页*/
function removeIframe() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

/************************************  修改页面  *****************************************/
if (this_activityId > 0) {
    // 查询接口
    $.ajax({
        url: root.promotion.copyActivityByActivityId + '?activityId=' + this_activityId,
        cache: false,  //禁用缓存
        type: "get",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        success: function (data) {
            if (data != null && data.errorCode == 0) {
                //  填充表单
                fillForm(data.data.activityBase, data.data.activityFullReductionList);
                // 转换bean 填充table
                // fillTable(editConvertSkus(data.data.activityProductList));
                $("#form-member").valid();
                $("#activityPerson").attr("disabled", true);
                $("#activityLocation").attr("disabled", true);
            } else {
                layer.msg(data.sub_msg, {
                    icon: 2,
                    time: 3000
                });
            }
        },
        error: function () {
            console.log("!!!!活动商品查询异常!!!!");
            layer.msg('活动商品查询异常', {
                icon: 2,
                time: 3000
            });
        }
    });
}

var formMinDateTime = "";

// 编辑表单内容回显
function fillForm(data, reduceData) {
    crmCustomerIdOnearry=[]
    // 满减区域回显
    if (reduceData.length > 0) {
        $("#fullReductionWay").val(reduceData[0].fullReductionWay);
        changeFullReductionWay();
        $("#fixGrade-" + reduceData[0].fixGrade).prop("checked", true);
        if (reduceData[0].fixGrade == 10) {
            $("#useCondition-" + reduceData[0].fullReductionWay).val(reduceData[0].useCondition);
            $("#ruleType-" + reduceData[0].ruleType).prop("checked", true);
            $("#ruleValue-" + reduceData[0].ruleType).val(reduceData[0].ruleValue);
            ruleTypeChange();
            $("#preferentialMost").val(0);
            if (reduceData[0].preferentialMost != 0) {
                $("#ispreferentialMost").prop("checked", false);
                $("#preferentialMost_show").css('display', 'inline');
                $("#preferentialMost").val(reduceData[0].preferentialMost);
            }
        } else {
            $("#addOneTr").attr("disabled", false);
            // 填充table
            for (let i = 0; i < reduceData.length; i++) {
                changeAllReductionWay();
                const reduce = reduceData[i];
                var row = i + 1;
                $("#useCondition-" + reduce.fullReductionWay + "-" + row).val(reduce.useCondition);
                if (reduce.ruleType == 10) {
                    $("#ruleType-count-" + row).prop("checked", true);
                    $("#roleValue-count-" + row).val(reduce.ruleValue);
                } else {
                    $("#ruleType-reduce-" + row).prop("checked", true);
                    $("#roleValue-reduce-" + row).val(reduce.ruleValue);
                }
                if (row + 1 > 1 && row + 1 <= reduceData.length) {
                    addTr();
                }
            }
        }
    }
    // ***************公共区域
    $("#activityName").val(data.activityName);
    formMinDateTime = data.startTime;
    $("#startTime").val(data.startTime);
    $("#endTime").val(data.endTime);
    $("#activityPerson").val(data.activityPerson);
    crmCustomerIdOnearry.push($("#activityPerson").val())
    $("#activityLocation").val(data.activityLocation);

    $("#enableCategoryDiscount").val(data.enableCategoryDiscount);
    $("#categoryDiscountRule").val(data.categoryDiscountRule);
    $("#categoryDiscount").val(data.categoryDiscount);

    $("#platform-" + data.platform).prop("checked", true);

    if (data.platform == 10) {
        $('#adPcUrl').attr("disabled", false);
        $('#adAppUrl').attr("disabled", false);
        $('#platform-20').prop("checked", true);
        $('#platform-30').prop("checked", true);
    } else {
        if (data.platform == 20) {
            $('#adPcUrl').attr("disabled", false);
        }
        if (data.platform == 30) {
            $('#adAppUrl').attr("disabled", false);
        }
    }

    if (data.payWay != null && data.payWay.length > 0) {
        var pay = data.payWay.split(",");
        for (let i = 0; i < pay.length; i++) {
            const way = pay[i];
            $("#payWay-" + way).prop("checked", true);
        }
    }
    $("#advertisingWords").val(data.advertisingWords);
    $("#adPcUrl").val(data.adPcUrl);
    $("#adAppUrl").val(data.adAppUrl);
    if (data.activityPerson != 10) { // 签约客户可以设置品类折扣率价格商品是否参与
        $('#discount').show();
        $("#payWay-1101-show").show();
        $("#payWay-1201-show").show();
        $("#payWay-1701-show").hide();
    }

    if (data.enableCategoryDiscount == 10) {
        $("#categoryDiscountRule_show").show();
    }
    if (data.categoryDiscountRule != 10) {
        $("#categoryDiscount_show").show();
    }
}

// table回显
function fillTable(data) {
    setSkuLists = data;
    setSpuCodes = [];
    setSkuCodes = [];
    for (let i = 0; i < data.length; i++) {
        const sku = data[i];
        insertToSetSku(sku._spuCode, sku._skuCode);
        if (sku._spuSkuActivity == 10) {
            insertToSetSpu(sku._spuCode);
        }
    }
}

// 表单搜索条件重置
function resetSearch() {
    $(".category_inp").val("");
    _categoryData = {};
    $("#state").find("option:contains('状态')").prop("selected", true);
    $("#spuCode").val("");
    $("#skuCode").val("");
    $("#productCode").val("");
    $("#helpCode").val("");
    $("#spuName").val("");
    $("#brand").val("");
}

function minDataTime() {
    if (this_activityId > 0) {
        var date = new Date(formMinDateTime); //时间对象
        var str = date.getTime(); //转换成时间戳
        var timestamp = (new Date()).getTime();
        if (str > timestamp) {
            return '%y-%M-%d %H:00:00';
        }
        return formMinDateTime;
    } else {
        return '%y-%M-%d %H:00:00';
    }
}

function maxDataTime() {
    var valstart = $("#startTime").val();
    if (valstart == "") {
        return '%y-%M-%d %H:00:00';
    } else {
        var date = new Date(formMinDateTime); //时间对象
        var start = date.getTime(); //转换成时间戳
        var now = new Date().Format("yyyy-MM-dd HH");
        var timestamp = new Date(now + ":00:00").getTime();
        if (start < timestamp) {
            return '%y-%M-%d %H:00:00';
        } else {
            return valstart;
        }
    }
}

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
